Append / Prepend items to an Array
There are four methods used to append/prepend items to an Array. They are:
- Array push method
- Array pop method
- Array unshift method
- Array shift method
Push
Use .push()
to add one or more items from the end of an array.
Syntax
push(element0)
push(element0, element1)
push(element0, element1, ..., elementN)
Example
var array = [3, 4, 5, 6];
array.push(1, 2);
console.log(array);
// expected output: [3, 4, 5, 6, 1, 2];
A new array is returned with new length.
Pop
The .push()
is used to remove the last element from the array and returns this element.
Syntax
pop()
Example
var array = [3, 2, 9, 15, 22, 1];
var poppedElement = array.pop();
console.log(poppedElement);
// expected output: 1
console.log(array);
// expected output: [2, 9, 15, 22]
var poppedElement = array.pop();
console.log(poppedElement);
// expected output: 22
console.log(array);
// expected output: [1, 2, 9, 15]
At a time, one element can be popped from the array.
Unshift
The .unshift()
method is used to insert one or more elements at the start/beginning of the array
Syntax
unshift(element0)
unshift(element0, element1)
unshift(element0, element1, ..., elementN)
Example
var array = [12, 5, 4, 23];
array.unshift(20, 55, [10, 21]);
console.log(array);
A new array is returned with new length.
Shift
The .shift()
method is used to remove the first element from the array.
Syntax
shift()
Example
var array = [12, 15, 25, 66, 1];
var shiftedElement = array.shift();
console.log(shiftedElement);
// expected output: 12
console.log(array);
// expected output: [15, 25, 66, 1];
var shiftedElement = array.shift();
console.log(shiftedElement);
// expected output: 15
console.log(array);
// expected output: [25, 66, 1];